<!-- 门店入驻 -->
<template>
	<view class="apply-commission-wrap page_box">
		<!-- 标题栏 -->
<!-- 		<view class="head-box" >
			<u-navbar :isFixed="false" :borderBottom="false" back-icon-color="#fff" :background="{}"></u-navbar>
		</view> -->
		<u-navbar :isFixed="false" :borderBottom="false" back-icon-color="#333" :background="{}"></u-navbar>

		<!-- 表单 -->
		<view class="apply-form content_box">
			<u-form :model="{...model}" :rules="rules" ref="uForm" :errorType="errorType">
				<u-form-item :labelStyle="labelStyle" 　 label-width="150" label-position="left" label="申请区域"
					prop="area_name">
					<u-input type="select" :select-open="cityPickerShow" v-model="model.area_name" placeholder="请选择地区" 
						@click="cityPickerShow = true"></u-input>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" 　 label-width="150" label-position="left" label="法定代表人"
					prop="realname">
					<u-input placeholder="请输入法定代表人姓名" :placeholderStyle="placeholderStyle" v-model="model.realname"
						type="text"></u-input>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" 　 label-width="150" label-position="left" label="企业名称"
					prop="company_name">
					<u-input placeholder="请输入企业名称" :placeholderStyle="placeholderStyle" v-model="model.company_name"
						type="text"></u-input>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" label-position="left" label="联系电话" prop="phone" label-width="150">
					<u-input placeholder="请输入法定代表人手机号" :placeholderStyle="placeholderStyle" v-model="model.phone"
						type="number"></u-input>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" 　 label-width="150" label-position="left" label="企业注册地"
					prop="company_area_value">
					<u-input type="select" :select-open="pickerShow" v-model="model.company_area_value" placeholder="请选择地区" 
						@click="pickerShow = true"></u-input>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" label-width="150" label-position="left" label="详细地址"
					prop="company_address">
						<u-input type="text" v-model="model.company_address" placeholder="请输入详细地址"></u-input>
						<!-- <u-input
							type="textarea"
							disabled
							border
							placeholder="点击获取详细地址"
							:placeholderStyle="placeholderStyle"
							@click="chooseLocation"
							v-model="model.company_address"
						></u-input> -->
				</u-form-item>
			
				
				<u-form-item :labelStyle="labelStyle" prop="images" label="营业执照" label-position="top" label-width="150"
					:borderBottom="true">
					<u-upload :placeholderStyle="placeholderStyle" :showProgress="false"
						@on-uploaded="uploadSuccess($event, 'company_license_image')"
						@on-remove="uploadRemove($event, 'company_license_image')" :action="`${$API_URL}/index/upload`"
						:file-list="[{url:model.company_license_image}]"
						width="148" height="148" maxCount="1"></u-upload>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" label-width="180" label-position="left" label="对公账户名称"
					prop="company_bank_name">
					<u-input placeholder="请输入对公账户开户名称" :placeholderStyle="placeholderStyle"
						v-model="model.company_bank_name" type="text"></u-input>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" label-width="180" label-position="left" label="对公银行账号"
					prop="company_bank_card">
					<u-input placeholder="请输入对公银行账号" :placeholderStyle="placeholderStyle"
						v-model="model.company_bank_card" type="text"></u-input>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" label-width="180" label-position="left" label="对公开户行"
					prop="company_bank">
					<u-input placeholder="请输入对公开户行名称(具体到支行)" :placeholderStyle="placeholderStyle"
						v-model="model.company_bank" type="text"></u-input>
				</u-form-item>
				<u-form-item :labelStyle="labelStyle" prop="images" label="法定代表人身份证" label-position="top"
					label-width="150" :borderBottom="true">
					<u-upload :placeholderStyle="placeholderStyle" :showProgress="false"
						@on-uploaded="uploadSuccess($event, 'company_representative_idcard_front_image')"
						@on-remove="uploadRemove($event, 'company_representative_idcard_front_image')"
						:file-list="[{url:model.company_representative_idcard_front_image}]"
						:action="`${$API_URL}/index/upload`" uploadText="人像面" width="148" height="148" maxCount="1">
					</u-upload>
					<u-upload :placeholderStyle="placeholderStyle" :showProgress="false"
						@on-uploaded="uploadSuccess($event, 'company_representative_idcard_reverse_image')"
						@on-remove="uploadRemove($event, 'company_representative_idcard_reverse_image')"
						:file-list="[{url:model.company_representative_idcard_reverse_image}]"
						:action="`${$API_URL}/index/upload`" uploadText="国徽面" width="148" height="148" maxCount="1">
					</u-upload>
				</u-form-item>
				<view class="agreement u-flex u-col-center">
					<u-checkbox v-model="model.agreement" activeColor="#4CB89D" shape="circle" @change="onAgreement">
					</u-checkbox>
					<view class="agreement-text" @tap="toProtocol">勾选代表同意《代理入驻协议》</view>
				</view>
				<view class="u-flex u-row-center u-col-center"><button class="u-reset-button save-btn" @tap="onSubmit"
						:disabled="isFormEnd">确认提交</button></view>
			</u-form>
		</view>
		<u-select mode="mutil-column-auto" safe-area-inset-bottom
			:list="addressAreaList"
			v-model="cityPickerShow"
			@confirm="cityRegionConfirm">
		</u-select>
		
		<u-select mode="mutil-column-auto" safe-area-inset-bottom
			:list="addressAreaList"
			v-model="pickerShow"
			@confirm="regionConfirm">
		</u-select>
		<!-- 权限验证 -->
		<u-popup v-model="showNotice" mode="center" border-radius="20" :mask-close-able="false">
			<view class="notice-modal">
				<view class="img-wrap">
					<image class="notice-img" :src="authNotice.img" mode=""></image>
				</view>
				<view class="notice-title">{{ authNotice.title }}</view>
				<view class="notice-detail">{{ authNotice.detail || '' }}</view>
				<view class="goshop" v-if="authNotice.showbuybtn == 1" @tap="$Router.push(`/pages/goods/detail?id=${authNotice.showbuyid}`)">去购买资格商品</view>
					<button class="u-reset-button back-btn" @tap="hanldeResult()">{{authNotice.btnText}}</button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import Auth from '@/shopro/permission/index.js';
	import {
		mapMutations,
		mapActions,
		mapState
	} from 'vuex';
	export default {
		components: {},
		data() {
			return {
				showNotice: false,
				isFormEnd: false,
				authNotice: {},
				// 表单
				errorType: ['message'],
				pickerShow: false,
				cityPickerShow:false,
				selectShow: false,
				selectMode: 'mutil-column', // single-column, mutil-column, mutil-column-auto
				selectType: '',
				selectList: [],
				labelStyle: {
					'font-size': '28rpx',
					'font-weight': '500',
					color: '#333'
				},
				placeholderStyle: 'font-size: 28rpx;color:#c4c4c4;',
				model: {
					area:"",// 区域id
					area_name:"",// 申请区域名称（包含省市）
					realname:"",// 法人姓名
					company_name:"",// 企业名称
					phone:"",//联系电话
					company_province_name:"", //企业注册地-省-名称
					company_city_name:"",//企业注册地-市-名称
					company_area_name:"",//企业注册地-区-名称
					company_province_id:"",//企业注册地-省-id
					company_city_id:"",//企业注册地-市-id
					company_area_id:"",//企业注册地-区-id
					company_address:"",//企业详细地址
					company_bank:"",//对公账户开户行
					company_bank_name:"",//对公账户名称
					company_bank_card:"",// 对公账户账户
					company_license_image:"",// 企业图片
					company_representative_idcard_front_image:"", // 身份证正面
					company_representative_idcard_reverse_image:"",// 身份证反面
					company_area_value:"",//省市区的显示字段
				},
				image_obj:{
					company_license_image:"",// 企业图片
					company_representative_idcard_front_image:"", // 身份证正面
					company_representative_idcard_reverse_image:"",// 身份证反面
				},
				addressAreaList:[],
				agreement: false,
				status:0,
				rules: {
					name: [{
						required: true,
						message: '请输入商家名称',
						trigger: ['change', 'blur']
					}],
					realname: [{
						required: true,
						message: '请输入法定代表人姓名',
						trigger: ['change', 'blur']
					}],
					company_name: [{
						required: true,
						message: '请输入企业名称',
						trigger: ['change', 'blur']
					}],
					phone: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur']
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ['change', 'blur']
						}
					],
					company_area_value: [{
						required: true,
						message: '请选择所在地区',
						trigger: ['change', 'blur']
					}],
					area_name: [{
						required: true,
						message: '请选择所在地区',
						trigger: ['change', 'blur']
					}],
					company_address: [{
						required: true,
						message: '请输入详细地址',
						trigger: ['change', 'blur']
					}]
				}
			};
		},
		computed: {
			...mapState('shopro',['config'])
		},
		onLoad() {
			this.getStoreInfo();
			this.fetchArea();
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			hanldeResult(){
				if(this.status != -1){
					this.$Router.push(this.authNotice.btnPath)
				}
				this.showNotice = false;
			},
			async fetchArea() {
				this.$http('address.area').then(res => {
					if (res.code === 1) {
						let { provinceData, cityData, areaData } = res.data;
						provinceData.forEach((item, index) => {
							this.addressAreaList.push({...item, children: [] });
							this.addressAreaList[index].children.push(...cityData[index]);
							this.addressAreaList[index].children.forEach((item1, index1) => {
								item1['children'] = [];
								item1.children.push(...areaData[index][index1]);
							});
						
						});
					}
				});
			},
			regionConfirm(items) {
				this.model.company_area_value = items[0].label + '-' + items[1].label + '-' + items[2].label;
				this.model.company_province_name = items[0].label
				this.model.company_province_id = items[0].value;
				this.model.company_city_name = items[1].label;
				this.model.company_city_id = items[1].value;
				this.model.company_area_name = items[2].label;
				this.model.company_area_id = items[2].value;
			},
			cityRegionConfirm(items){
				this.model.area_name = items[0].label + '-' + items[1].label + '-' + items[2].label;
				this.model.area = items[2].value;
			},
			// 弹窗按钮
			onAuthBtn(path) {
				path &&
					this.$Router.push({
						path: path
					});
				this.showNotice = false;
			},
			// 上传图片成功
			uploadSuccess(e, type) {
				switch (type) {
					case 'company_license_image':
						this.image_obj.company_license_image = e[0].response.data.url;
						break;
					case 'company_representative_idcard_front_image':
						this.image_obj.company_representative_idcard_front_image = e[0].response.data.url;
						break
					case 'company_representative_idcard_reverse_image':
						this.image_obj.company_representative_idcard_reverse_image = e[0].response.data.url;
						break;
					default:
						return;
				}
			},
			// 移除图片
			uploadRemove(index, type) {
				switch (type) {
					case 'company_license_image':
						this.image_obj.company_license_image = "";
						this.model.company_license_image = "";
						break;
					case 'company_representative_idcard_front_image':
						this.image_obj.company_representative_idcard_front_image = "";
						this.model.company_representative_idcard_front_image = "";
						break
					case 'company_representative_idcard_reverse_image':
						this.image_obj.company_representative_idcard_reverse_image = "";
						this.model.company_representative_idcard_reverse_image  = "";
						break;
					default:
						return;
				}
			},
			// 地址选择
			async chooseLocation() {
				let authState = await new Auth('userLocation').check();
				authState &&
					uni.chooseLocation({
						success: res => {
							this.model.company_address = res.address + res.name;
						},
						fail: err => {
							console.log(err);
						}
					});
			},

			// 勾选同意
			onAgreement(e) {
				this.agreement = e.value;
			},

			// 门店详情
			getStoreInfo(isrefresh) {
				let that = this;
				that.$http('store.qudai_apply_detail',{mode:"xianqu"}).then(res => {
					if (res.code === 1) {
						res.data && this.authStatus(res.data,isrefresh);
					}
					if (res.code === 0){
						setTimeout(()=>{
							// that.$Router.push('/pages/index/user')
							this.$Router.back(2)
						},1500)
					}
				});
			},
			toProtocol() {
				// 跳转门店协议
				this.config?.shop && this.jump('/pages/public/richtext', {
					id: this.config?.shop?.xianqu_agent_protocol
				});
			},
			// 初始化model
			initModel() {
				
				// 初始化市区
				if (this.model.province_name) {
					this.model.area = `${this.model.province_name}-${this.model.city_name}-${this.model.area_name}`;
				}
				if (this.model.images_arr) {
					this.model.images_arr.forEach(item => {
						this.model.fileImages.push({
							url: item
						});
					});
				}
				// 协议
				this.$set(this.model, 'agreement', false);
			},

			// 状态鉴权
			authStatus(data,isrefresh) {
				this.status = data.status;
				switch (String(data.status)) {
					case '0':
						this.showNotice = true;
						if(isrefresh == 'refresh'){
							this.model.company_representative_idcard_front_image = '';
							this.model.company_representative_idcard_reverse_image = '';
							this.model = {
								...this.model,
							};
						}else {
							this.model = {
								...this.model,
								...data
							};
						}
						this.initModel();
						this.authNotice = {
							img: this.$IMG_URL + '/imgs/commission/auth_check.png',
							title: data.need_buy_goods == 1 ? '您的申请资料已提交！' : '您的申请正在审核中',
							detail: data.status_msg,
							showbuybtn: data.need_buy_goods,
							showbuyid: data.need_buy_goods == 1 ? data.qudai_agent_goods_id : '',
							btnText: '返回',
							btnPath: '/pages/index/user'
						};
						break;
					case '-1':
					this.model.company_area_value = data.company_province_name + '-' + data.company_city_name + '-' + data.company_area_name
						this.showNotice = true;
						this.model = {
							...this.model,
							...data
						};
						this.initModel();
						this.authNotice = {
							img: this.$IMG_URL + '/imgs/commission/auth_reject.png',
							title: '您的申请已被驳回！',
							detail: data.status_msg,
							btnText: '重新申请',
							btnPath: ''
						};
						break;
					case '1':
						this.showNotice = true;
						this.model = {
							...this.model,
							...data
						};
						this.initModel();
						this.authNotice = {
							img: this.$IMG_URL + '/imgs/commission/auth_check.png',
							title: '您当前已开通县区代理',
							btnText: '返回',
							btnPath: '/pages/index/user'
						};
						break;
				
					default:
				}
			},

			// 申请门店
			applyStore() {
				let that = this;
				this.isFormEnd = false;
				
				let params = {
					area:this.model.area, // 区域id
					area_name:this.model.area_name.replaceAll("-",""),// 申请区域名称（包含省市）
					realname:this.model.realname,// 法人姓名
					company_name:this.model.company_name,// 企业名称
					phone:this.model.phone,//联系电话
					company_province_name:this.model.company_province_name, //企业注册地-省-名称
					company_city_name:this.model.company_city_name,//企业注册地-市-名称
					company_area_name:this.model.company_area_name,//企业注册地-区-名称
					company_province_id:this.model.company_province_id,//企业注册地-省-id
					company_city_id:this.model.company_city_id,//企业注册地-市-id
					company_area_id:this.model.company_area_id,//企业注册地-区-id
					company_address:this.model.company_address,//企业详细地址
					company_bank:this.model.company_bank,//对公账户开户行
					company_bank_name:this.model.company_bank_name,//对公账户名称
					company_bank_card:this.model.company_bank_card,// 对公账户账户
					company_license_image:this.image_obj.company_license_image || this.model.company_license_image,// 企业图片
					company_representative_idcard_front_image:this.image_obj.company_representative_idcard_front_image || this.model.company_representative_idcard_front_image, // 身份证正面
					company_representative_idcard_reverse_image:this.image_obj.company_representative_idcard_reverse_image || this.model.company_representative_idcard_reverse_image,// 身份证反面
					mode:"xianqu"
				}
				console.log(params)
				if(this.status == -1){
					params.id = this.model.id
					that.$http('store.qudai_apply_edit', params, '提交中...').then(res => {
						if (res.code === 1) {
							this.isFormEnd = true;
							//  #ifdef MP-WEIXIN
							this.$store.dispatch('user/getMessageIds', 'storeApply');
							//  #endif
							// this.authStatus({
							// 	status: 0
							// });
							this.getStoreInfo("refresh")
						}
					});
					
					return
				}
				that.$http('store.qudai_apply', params, '提交中...').then(res => {
					if (res.code === 1) {
						this.isFormEnd = true;
						//  #ifdef MP-WEIXIN
						this.$store.dispatch('user/getMessageIds', 'storeApply');
						//  #endif
						// this.authStatus({
						// 	status: 0
						// });
						this.getStoreInfo("refresh")
					}
				});
			},

			// 提交
			onSubmit() {
				let that = this;
				console.log(this.image_obj)
				if (!this.image_obj.company_license_image.length && !this.model.company_license_image.length ) {
					this.$u.toast('请上传营业执照照片');
					return;
				}
				if (!this.image_obj.company_representative_idcard_front_image.length && !this.model.company_representative_idcard_front_image.length) {
					this.$u.toast('请上传身份证人像面');
					return;
				}
				if (!this.image_obj.company_representative_idcard_reverse_image.length && !this.model.company_representative_idcard_reverse_image.length) {
					this.$u.toast('请上传身份证国徽面');
					return;
				}
				this.$refs.uForm.validate(valid => {
					if (valid) {
						if (!this.agreement) return this.$u.toast('请勾选协议');
						this.applyStore();
					} else {
						this.$u.toast('请完善表单');
					}
				});
			},
			jump(path, parmas) {
				this.$Router.push({
					path: path,
					query: parmas
				});
			}
		}
	};
</script>

<style lang="scss">
	.apply-commission-wrap {
		background-color: #fff;

		.head-box {
			background: url($IMG_URL+'/imgs/user/sh_shop_apply_head.png') no-repeat;
			background-size: 100% auto;
			height: 370rpx;
		}
	}

	// 表单
	.apply-form {
		width: 750rpx;
		background: #ffffff;
		border-radius: 20rpx;
		padding: 30rpx;
	
	.agreement {
			margin-top: 20rpx;

			.agreement-text {
				font-size: 24rpx;
				font-weight: 500;
				color: #4cb89d;
			}
		}
	
	.save-btn {
			width: 690rpx;
			line-height: 86rpx;
			background: linear-gradient(90deg, #2dae9c, #6bc29e);
			box-shadow: 0px 7rpx 11rpx 2rpx rgba(61, 179, 156, 0.34);
			border-radius: 43rpx;
			font-weight: 500;
			color: #ffffff;
			margin: 30rpx 0;
		}
	}

	// 星期
	.week-modal {
		.week-modal--head {
			height: 100rpx;
			border-bottom: 1rpx solid $u-border-color;

			.text-cancel {
				color: #ccc;
			}

			.text-green {
				color: #18b566;
			}
		}

		.week-modal--content {
			.week-btn {
				margin-right: 20rpx;
				margin-bottom: 20rpx;

				&:nth-of-type(3n) {
					margin-right: 0;
				}
			}
		}
	}

	// 提示
	.notice-modal {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		width: 612rpx;
		min-height: 658rpx;
		background: #ffffff;
		padding: 30rpx;
		border-radius: 20rpx;

		.img-wrap {
			margin-bottom: 50rpx;

			.notice-img {
				width: 180rpx;
				height: 170rpx;
			}
		}

		.notice-title {
			font-size: 35rpx;
			font-weight: bold;
			color: #46351b;
			margin-bottom: 28rpx;
		}

		.notice-detail {
			font-size: 28rpx;
			font-weight: 400;
			color: #999999;
			line-height: 36rpx;
			margin-bottom: 50rpx;
		}

		.notice-btn {
			width: 492rpx;
			height: 70rpx;
			line-height: 70rpx;
			background: linear-gradient(90deg, #2dae9c, #6bc29e);
			box-shadow: 0 7rpx 11rpx 2rpx rgba(61, 179, 156, 0.34);
			border-radius: 35rpx;
			font-size: 28rpx;
			font-weight: 500;
			color: #ffffff;
			margin-bottom: 10rpx;
		}

		.back-btn {
			width: 492rpx;
			height: 70rpx;
			line-height: 70rpx;
			font-size: 28rpx;
			font-weight: 500;
			color: #3ab29c;
			background: none;
		}
		.goshop{
			background: #fc7205;
			padding: 10rpx 20rpx;
			border-radius: 10rpx;
			font-size: 28rpx;
			color: #FFF;
			margin-bottom: 20rpx;
		}
	}
</style>
